import _ from 'lodash';
import React, { useEffect } from 'react';
import { Button, Dropdown, Checkbox, Tree, message } from 'antd';

import { HttpCode } from '#/utils/contacts.js';
import { useStaticState, useTRState } from '#/utils/trHooks.jsx';
import { SettingOutlined } from '#/utils/antdIcons.js';

import styles from './index.less';
import { saveDynamicColumns } from '../../services';

export default ({ columns = [], regionCode, menuCode, fetch = () => {} }) => {
  const [state, setState] = useTRState({
    indeterminate: false,
    checkAll: false,
    open: false,
    selectedKeys: [],
    loading: false,
  });
  const staticData = useStaticState({
    allDataObj: {},
    allKeys: [],
    disabledKeys: [],
  });

  const flattenDeep = (list = [], selectedObj = {}) => {
    list?.forEach((l) => {
      selectedObj[l.key] = _.cloneDeep(l);
      l?.children?.length && flattenDeep(l.children, selectedObj);
    });
    return selectedObj;
  };

  const flattenDeepKey = (list = []) => {
    const selectedKeys = [];
    list?.forEach((l) => {
      let childrenObj = {};
      childrenObj = flattenDeep(l?.children || [], childrenObj);
      // 默认选中
      if (
        (l?.checkbox === 1 && l?.key) ||
        (Object.values(childrenObj)?.length &&
          Object.values(childrenObj)?.filter((c) => c?.checkbox === 1)?.length ===
            Object.values(childrenObj)?.length)
      ) {
        selectedKeys.push(l.key);
      }
      // 所有选项
      if ((!l?.disabled || (l?.disabled && l?.checkbox === 1)) && l?.key) {
        staticData.allKeys.push(l.key);
      }
      // 禁止选择中 选中的
      if (l?.disabled && l?.checkbox === 1 && l?.key) {
        staticData.disabledKeys.push(l.key);
      }
    });
    return selectedKeys;
  };
  const setColumns = () => {
    let selectedKeys = [];
    const selectedObj = {};
    staticData.allDataObj = flattenDeep(columns, selectedObj);
    selectedKeys = flattenDeepKey(Object.values(staticData.allDataObj));

    setState({
      selectedKeys,
      indeterminate: !!selectedKeys.length && selectedKeys.length < staticData.allKeys.length,
      checkAll: selectedKeys.length === staticData.allKeys.length,
    });
  };
  useEffect(() => {
    setColumns();
    return () => {
      staticData.allKeys = [];
      staticData.disabledKeys = [];
    };
  }, [columns]);

  const onCheckAllChange = (e) => {
    Object.values(staticData.allDataObj)?.forEach((s) => {
      if (s.checkbox !== undefined) {
        s.checkbox = e?.target.checked ? 1 : 0;
      }
    });
    setState({
      selectedKeys: e?.target.checked ? staticData.allKeys : staticData.disabledKeys,
      indeterminate: false,
      checkAll: e?.target.checked,
    });
  };
  const onCheck = (selectedKeys) => {
    Object.values(staticData.allDataObj)?.forEach((s) => {
      if (s.checkbox !== undefined) {
        s.checkbox = selectedKeys.includes(s?.key) ? 1 : 0;
      }
    });

    setState({
      selectedKeys,
      indeterminate: !!selectedKeys.length && selectedKeys.length < staticData.allKeys.length,
      checkAll: selectedKeys.length === staticData.allKeys.length,
    });
  };
  const transformationTree = (list = []) => {
    const array = list?.map((a) => {
      const slide = _.cloneDeep(staticData.allDataObj[a.key]);
      let children = [];
      if (a?.children?.length) {
        children = transformationTree(a.children);
        slide.children = _.cloneDeep(children);
      }
      return slide;
    });
    return array;
  };
  const onSuccess = async () => {
    setState({
      loading: true,
    });
    const array = transformationTree(_.cloneDeep(columns));
    const params = {
      regionCode,
      menuCode,
      array,
    };
    const res = await saveDynamicColumns(params);
    if (res?.statusCode === HttpCode.SUCCESS) {
      setState({
        open: false,
      });
      fetch && fetch();
    } else {
      message.error(res?.message || '保存失败');
    }
    setState({
      loading: false,
    });
  };

  const renderColumns = () => {
    return (
      <div className={styles.container}>
        <div className={styles.container_header}>
          <Checkbox
            indeterminate={state.indeterminate}
            onChange={onCheckAllChange}
            checked={state.checkAll}
          >
            全选
          </Checkbox>
        </div>
        <div className={styles.container_tree}>
          <Tree checkable onCheck={onCheck} checkedKeys={state.selectedKeys} treeData={columns} />
        </div>
        <div className={styles.container_footer}>
          <Button
            size={'small'}
            style={{ marginRight: 8 }}
            onClick={() =>
              setState({
                open: false,
              })
            }
            loading={state.loading}
          >
            取消
          </Button>
          <Button
            size={'small'}
            type={'primary'}
            onClick={() => onSuccess()}
            loading={state.loading}
          >
            确认
          </Button>
        </div>
      </div>
    );
  };

  return (
    <Dropdown
      overlay={renderColumns}
      onVisibleChange={() =>
        setState({
          open: true,
        })
      }
      placement="bottomRight"
      trigger={['click']}
      visible={state.open}
    >
      <SettingOutlined
        style={{ fontSize: 12, cursor: 'pointer', position: 'absolute', right: 115, top: 24 }}
      />
    </Dropdown>
  );
};
